3 * Base code for file repositories.
10 * Base class for file repositories.
11 * Do not instantiate, use a derived class.
15 abstract class FileRepo
{
17 const DELETE_SOURCE
= 1;
19 const OVERWRITE_SAME
= 4;
20 const SKIP_VALIDATION
= 8;
22 var $thumbScriptUrl, $transformVia404;
23 var $descBaseUrl, $scriptDirUrl, $scriptExtension, $articleUrl;
24 var $fetchDescription, $initialCapital;
25 var $pathDisclosureProtection = 'paranoid';
26 var $descriptionCacheExpiry, $hashLevels, $url, $thumbUrl;
29 * Factory functions for creating new files
30 * Override these in the base class
32 var $fileFactory = false, $oldFileFactory = false;
33 var $fileFactoryKey = false, $oldFileFactoryKey = false;
35 function __construct( $info ) {
37 $this->name
= $info['name'];
40 $this->initialCapital
= MWNamespace
::isCapitalized( NS_FILE
);
41 foreach ( array( 'descBaseUrl', 'scriptDirUrl', 'articleUrl', 'fetchDescription',
42 'thumbScriptUrl', 'initialCapital', 'pathDisclosureProtection',
43 'descriptionCacheExpiry', 'hashLevels', 'url', 'thumbUrl', 'scriptExtension' )
46 if ( isset( $info[$var] ) ) {
47 $this->$var = $info[$var];
50 $this->transformVia404
= !empty( $info['transformVia404'] );
54 * Determine if a string is an mwrepo:// URL
56 static function isVirtualUrl( $url ) {
57 return substr( $url, 0, 9 ) == 'mwrepo://';
61 * Create a new File object from the local repository
63 * @param $title Mixed: Title object or string
64 * @param $time Mixed: Time at which the image was uploaded.
65 * If this is specified, the returned object will be an
66 * instance of the repository's old file class instead of a
67 * current file. Repositories not supporting version control
68 * should return false if this parameter is set.
72 function newFile( $title, $time = false ) {
73 if ( !($title instanceof Title
) ) {
74 $title = Title
::makeTitleSafe( NS_FILE
, $title );
75 if ( !is_object( $title ) ) {
80 if ( $this->oldFileFactory
) {
81 return call_user_func( $this->oldFileFactory
, $title, $this, $time );
86 return call_user_func( $this->fileFactory
, $title, $this );
91 * Find an instance of the named file created at the specified time
92 * Returns false if the file does not exist. Repositories not supporting
93 * version control should return false if the time is specified.
95 * @param $title Mixed: Title object or string
96 * @param $options Associative array of options:
97 * time: requested time for an archived image, or false for the
98 * current version. An image object will be returned which was
99 * created at the specified time.
101 * ignoreRedirect: If true, do not follow file redirects
103 * private: If true, return restricted (deleted) files if the current
104 * user is allowed to view them. Otherwise, such files will not
107 function findFile( $title, $options = array() ) {
108 $time = isset( $options['time'] ) ?
$options['time'] : false;
109 if ( !($title instanceof Title
) ) {
110 $title = Title
::makeTitleSafe( NS_FILE
, $title );
111 if ( !is_object( $title ) ) {
115 # First try the current version of the file to see if it precedes the timestamp
116 $img = $this->newFile( $title );
120 if ( $img->exists() && ( !$time ||
$img->getTimestamp() == $time ) ) {
123 # Now try an old version of the file
124 if ( $time !== false ) {
125 $img = $this->newFile( $title, $time );
126 if ( $img && $img->exists() ) {
127 if ( !$img->isDeleted(File
::DELETED_FILE
) ) {
129 } else if ( !empty( $options['private'] ) && $img->userCan(File
::DELETED_FILE
) ) {
136 if ( !empty( $options['ignoreRedirect'] ) ) {
139 $redir = $this->checkRedirect( $title );
140 if( $redir && $title->getNamespace() == NS_FILE
) {
141 $img = $this->newFile( $redir );
145 if( $img->exists() ) {
146 $img->redirectedFrom( $title->getDBkey() );
154 * Find many files at once.
155 * @param $items An array of titles, or an array of findFile() options with
156 * the "title" option giving the title. Example:
158 * $findItem = array( 'title' => $title, 'private' => true );
159 * $findBatch = array( $findItem );
160 * $repo->findFiles( $findBatch );
162 function findFiles( $items ) {
164 foreach ( $items as $item ) {
165 if ( is_array( $item ) ) {
166 $title = $item['title'];
168 unset( $options['title'] );
173 $file = $this->findFile( $title, $options );
175 $result[$file->getTitle()->getDBkey()] = $file;
182 * Create a new File object from the local repository
183 * @param $sha1 Mixed: base 36 SHA-1 hash
184 * @param $time Mixed: time at which the image was uploaded.
185 * If this is specified, the returned object will be an
186 * of the repository's old file class instead of a current
187 * file. Repositories not supporting version control should
188 * return false if this parameter is set.
192 function newFileFromKey( $sha1, $time = false ) {
194 if ( $this->oldFileFactoryKey
) {
195 return call_user_func( $this->oldFileFactoryKey
, $sha1, $this, $time );
200 return call_user_func( $this->fileFactoryKey
, $sha1, $this );
205 * Find an instance of the file with this key, created at the specified time
206 * Returns false if the file does not exist. Repositories not supporting
207 * version control should return false if the time is specified.
209 * @param $sha1 String base 36 SHA-1 hash
210 * @param $options Option array, same as findFile().
212 function findFileFromKey( $sha1, $options = array() ) {
213 $time = isset( $options['time'] ) ?
$options['time'] : false;
215 # First try the current version of the file to see if it precedes the timestamp
216 $img = $this->newFileFromKey( $sha1 );
220 if ( $img->exists() && ( !$time ||
$img->getTimestamp() == $time ) ) {
223 # Now try an old version of the file
224 if ( $time !== false ) {
225 $img = $this->newFileFromKey( $sha1, $time );
226 if ( $img->exists() ) {
227 if ( !$img->isDeleted(File
::DELETED_FILE
) ) {
229 } else if ( !empty( $options['private'] ) && $img->userCan(File
::DELETED_FILE
) ) {
238 * Get the URL of thumb.php
240 function getThumbScriptUrl() {
241 return $this->thumbScriptUrl
;
245 * Get the URL corresponding to one of the four basic zones
246 * @param $zone String: one of: public, deleted, temp, thumb
247 * @return String or false
249 function getZoneUrl( $zone ) {
254 * Returns true if the repository can transform files via a 404 handler
256 function canTransformVia404() {
257 return $this->transformVia404
;
261 * Get the name of an image from its title object
262 * @param $title Title
264 function getNameFromTitle( $title ) {
265 if ( $this->initialCapital
!= MWNamespace
::isCapitalized( NS_FILE
) ) {
267 $name = $title->getUserCaseDBKey();
268 if ( $this->initialCapital
) {
269 $name = $wgContLang->ucfirst( $name );
272 $name = $title->getDBkey();
277 static function getHashPathForLevel( $name, $levels ) {
278 if ( $levels == 0 ) {
281 $hash = md5( $name );
283 for ( $i = 1; $i <= $levels; $i++
) {
284 $path .= substr( $hash, 0, $i ) . '/';
291 * Get a relative path including trailing slash, e.g. f/fa/
292 * If the repo is not hashed, returns an empty string
294 function getHashPath( $name ) {
295 return self
::getHashPathForLevel( $name, $this->hashLevels
);
299 * Get the name of this repository, as specified by $info['name]' to the constructor
306 * Make an url to this repo
308 * @param $query mixed Query string to append
309 * @param $entry string Entry point; defaults to index
312 function makeUrl( $query = '', $entry = 'index' ) {
313 $ext = isset( $this->scriptExtension
) ?
$this->scriptExtension
: '.php';
314 return wfAppendQuery( "{$this->scriptDirUrl}/{$entry}{$ext}", $query );
318 * Get the URL of an image description page. May return false if it is
319 * unknown or not applicable. In general this should only be called by the
320 * File class, since it may return invalid results for certain kinds of
321 * repositories. Use File::getDescriptionUrl() in user code.
323 * In particular, it uses the article paths as specified to the repository
324 * constructor, whereas local repositories use the local Title functions.
326 function getDescriptionUrl( $name ) {
327 $encName = wfUrlencode( $name );
328 if ( !is_null( $this->descBaseUrl
) ) {
329 # "http://example.com/wiki/Image:"
330 return $this->descBaseUrl
. $encName;
332 if ( !is_null( $this->articleUrl
) ) {
333 # "http://example.com/wiki/$1"
335 # We use "Image:" as the canonical namespace for
336 # compatibility across all MediaWiki versions.
337 return str_replace( '$1',
338 "Image:$encName", $this->articleUrl
);
340 if ( !is_null( $this->scriptDirUrl
) ) {
341 # "http://example.com/w"
343 # We use "Image:" as the canonical namespace for
344 # compatibility across all MediaWiki versions,
345 # and just sort of hope index.php is right. ;)
346 return $this->makeUrl( "title=Image:$encName" );
352 * Get the URL of the content-only fragment of the description page. For
353 * MediaWiki this means action=render. This should only be called by the
354 * repository's file class, since it may return invalid results. User code
355 * should use File::getDescriptionText().
356 * @param $name String: name of image to fetch
357 * @param $lang String: language to fetch it in, if any.
359 function getDescriptionRenderUrl( $name, $lang = null ) {
360 $query = 'action=render';
361 if ( !is_null( $lang ) ) {
362 $query .= '&uselang=' . $lang;
364 if ( isset( $this->scriptDirUrl
) ) {
365 return $this->makeUrl(
367 wfUrlencode( 'Image:' . $name ) .
370 $descUrl = $this->getDescriptionUrl( $name );
372 return wfAppendQuery( $descUrl, $query );
380 * Get the URL of the stylesheet to apply to description pages
383 function getDescriptionStylesheetUrl() {
384 if ( $this->scriptDirUrl
) {
385 return $this->makeUrl( 'title=MediaWiki:Filepage.css&' .
386 wfArrayToCGI( Skin
::getDynamicStylesheetQuery() ) );
391 * Store a file to a given destination.
393 * @param $srcPath String: source path or virtual URL
394 * @param $dstZone String: destination zone
395 * @param $dstRel String: destination relative path
396 * @param $flags Integer: bitwise combination of the following flags:
397 * self::DELETE_SOURCE Delete the source file after upload
398 * self::OVERWRITE Overwrite an existing destination file instead of failing
399 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
400 * same contents as the source
401 * @return FileRepoStatus
403 function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
404 $status = $this->storeBatch( array( array( $srcPath, $dstZone, $dstRel ) ), $flags );
405 if ( $status->successCount
== 0 ) {
412 * Store a batch of files
414 * @param $triplets Array: (src,zone,dest) triplets as per store()
415 * @param $flags Integer: flags as per store
417 abstract function storeBatch( $triplets, $flags = 0 );
420 * Pick a random name in the temp zone and store a file to it.
421 * Returns a FileRepoStatus object with the URL in the value.
423 * @param $originalName String: the base name of the file as specified
424 * by the user. The file extension will be maintained.
425 * @param $srcPath String: the current location of the file.
427 abstract function storeTemp( $originalName, $srcPath );
431 * Append the contents of the source path to the given file.
432 * @param $srcPath String: location of the source file
433 * @param $toAppendPath String: path to append to.
434 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
435 * that the source file should be deleted if possible
436 * @return mixed Status or false
438 abstract function append( $srcPath, $toAppendPath, $flags = 0 );
441 * Remove a temporary file or mark it for garbage collection
442 * @param $virtualUrl String: the virtual URL returned by storeTemp
443 * @return Boolean: true on success, false on failure
446 function freeTemp( $virtualUrl ) {
451 * Copy or move a file either from the local filesystem or from an mwrepo://
452 * virtual URL, into this repository at the specified destination location.
454 * Returns a FileRepoStatus object. On success, the value contains "new" or
455 * "archived", to indicate whether the file was new with that name.
457 * @param $srcPath String: the source path or URL
458 * @param $dstRel String: the destination relative path
459 * @param $archiveRel String: rhe relative path where the existing file is to
460 * be archived, if there is one. Relative to the public zone root.
461 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
462 * that the source file should be deleted if possible
464 function publish( $srcPath, $dstRel, $archiveRel, $flags = 0 ) {
465 $status = $this->publishBatch( array( array( $srcPath, $dstRel, $archiveRel ) ), $flags );
466 if ( $status->successCount
== 0 ) {
469 if ( isset( $status->value
[0] ) ) {
470 $status->value
= $status->value
[0];
472 $status->value
= false;
478 * Publish a batch of files
479 * @param $triplets Array: (source,dest,archive) triplets as per publish()
480 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
481 * that the source files should be deleted if possible
483 abstract function publishBatch( $triplets, $flags = 0 );
485 function fileExists( $file, $flags = 0 ) {
486 $result = $this->fileExistsBatch( array( $file ), $flags );
491 * Checks existence of an array of files.
493 * @param $files Array: URLs (or paths) of files to check
494 * @param $flags Integer: bitwise combination of the following flags:
495 * self::FILES_ONLY Mark file as existing only if it is a file (not directory)
496 * @return Either array of files and existence flags, or false
498 abstract function fileExistsBatch( $files, $flags = 0 );
501 * Move a group of files to the deletion archive.
503 * If no valid deletion archive is configured, this may either delete the
504 * file or throw an exception, depending on the preference of the repository.
506 * The overwrite policy is determined by the repository -- currently FSRepo
507 * assumes a naming scheme in the deleted zone based on content hash, as
508 * opposed to the public zone which is assumed to be unique.
510 * @param $sourceDestPairs Array of source/destination pairs. Each element
511 * is a two-element array containing the source file path relative to the
512 * public root in the first element, and the archive file path relative
513 * to the deleted zone root in the second element.
514 * @return FileRepoStatus
516 abstract function deleteBatch( $sourceDestPairs );
519 * Move a file to the deletion archive.
520 * If no valid deletion archive exists, this may either delete the file
521 * or throw an exception, depending on the preference of the repository
522 * @param $srcRel Mixed: relative path for the file to be deleted
523 * @param $archiveRel Mixed: relative path for the archive location.
524 * Relative to a private archive directory.
525 * @return FileRepoStatus object
527 function delete( $srcRel, $archiveRel ) {
528 return $this->deleteBatch( array( array( $srcRel, $archiveRel ) ) );
532 * Get properties of a file with a given virtual URL
533 * The virtual URL must refer to this repo
534 * Properties should ultimately be obtained via File::getPropsFromPath()
536 abstract function getFileProps( $virtualUrl );
539 * Call a callback function for every file in the repository
540 * May use either the database or the filesystem
543 function enumFiles( $callback ) {
544 throw new MWException( 'enumFiles is not supported by ' . get_class( $this ) );
548 * Determine if a relative path is valid, i.e. not blank or involving directory traveral
550 function validateFilename( $filename ) {
551 if ( strval( $filename ) == '' ) {
554 if ( wfIsWindows() ) {
555 $filename = strtr( $filename, '\\', '/' );
558 * Use the same traversal protection as Title::secureAndSplit()
560 if ( strpos( $filename, '.' ) !== false &&
561 ( $filename === '.' ||
$filename === '..' ||
562 strpos( $filename, './' ) === 0 ||
563 strpos( $filename, '../' ) === 0 ||
564 strpos( $filename, '/./' ) !== false ||
565 strpos( $filename, '/../' ) !== false ) )
574 * Path disclosure protection functions
576 function paranoidClean( $param ) { return '[hidden]'; }
577 function passThrough( $param ) { return $param; }
580 * Get a callback function to use for cleaning error message parameters
582 function getErrorCleanupFunction() {
583 switch ( $this->pathDisclosureProtection
) {
585 $callback = array( $this, 'passThrough' );
587 default: // 'paranoid'
588 $callback = array( $this, 'paranoidClean' );
595 * Create a new fatal error
597 function newFatal( $message /*, parameters...*/ ) {
598 $params = func_get_args();
599 array_unshift( $params, $this );
600 return call_user_func_array( array( 'FileRepoStatus', 'newFatal' ), $params );
604 * Create a new good result
606 function newGood( $value = null ) {
607 return FileRepoStatus
::newGood( $this, $value );
611 * Delete files in the deleted directory if they are not referenced in the filearchive table
614 function cleanupDeletedBatch( $storageKeys ) {}
617 * Checks if there is a redirect named as $title. If there is, return the
618 * title object. If not, return false.
621 * @param $title Title of image
624 function checkRedirect( $title ) {
629 * Invalidates image redirect cache related to that image
630 * Doesn't do anything for repositories that don't support image redirects.
633 * @param $title Title of image
635 function invalidateImageRedirect( $title ) {}
638 * Get an array or iterator of file objects for files that have a given
639 * SHA-1 content hash.
643 function findBySha1( $hash ) {
648 * Get the human-readable name of the repo.
651 public function getDisplayName() {
652 // We don't name our own repo, return nothing
653 if ( $this->isLocal() ) {
656 // 'shared-repo-name-wikimediacommons' is used when $wgUseInstantCommons = true
657 return wfMessageFallback( 'shared-repo-name-' . $this->name
, 'shared-repo' )->text();
661 * Returns true if this the local file repository.
666 return $this->getName() == 'local';
671 * Get a key on the primary cache for this repository.
672 * Returns false if the repository's cache is not accessible at this site.
673 * The parameters are the parts of the key, as for wfMemcKey().
677 function getSharedCacheKey( /*...*/ ) {
682 * Get a key for this repo in the local cache domain. These cache keys are
683 * not shared with remote instances of the repo.
684 * The parameters are the parts of the key, as for wfMemcKey().
686 function getLocalCacheKey( /*...*/ ) {
687 $args = func_get_args();
688 array_unshift( $args, 'filerepo', $this->getName() );
689 return call_user_func_array( 'wfMemcKey', $args );
693 * Get an UploadStash associated with this repo.
695 * @return UploadStash
697 function getUploadStash() {
698 return new UploadStash( $this );